package com.jcli.jb51_net.article._198500_基于TCP协议网络socket编程;

import java.io.*;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

/**
 * 基础代码。
 */
public class TCPClient {

    private Socket socket;
    private BufferedReader br;
    private PrintWriter pw;

    // 构造方法，创建客户端套接字并初始化输入输出流
    public TCPClient(String serverAddress, int serverPort) {
        try {
            // 创建客户端套接字，连接到指定的服务器地址和端口
            socket = new Socket(serverAddress, serverPort);
            // 获取输入输出流
            br = getReader(socket); // 字符串输入流
            pw = getWriter(socket); // 字符串输出流
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 实现网络通信发送方法
    public void send(String msg) {
        // 输出字符流，由socket调用系统底层函数，经网卡发送字节流
        pw.println(msg);
    }

    // 实现网络通信接收方法
    public String receive() {
        String msg = null;
        try {
            // 从网络输入字符流中读取信息，每次只能接受一行信息
            // 不够一行时（无行结束符），该语句阻塞
            // 直到条件满足，程序往下运行
            msg = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;
    }

    // 定义网络连接关闭方法供外部调用
    public void close() {
        try {
            if (socket != null)
                socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 获取输入流
    private BufferedReader getReader(Socket socket) throws IOException {
        InputStream socketInStream = socket.getInputStream();
        return new BufferedReader(new InputStreamReader(socketInStream));
    }

    // 获取输出流
    private PrintWriter getWriter(Socket socket) throws IOException {
        OutputStream socketOutStream = socket.getOutputStream();
        return new PrintWriter(socketOutStream, true);
    }

    public static void main(String[] args) {
        // 指定服务器地址和端口
        String serverAddress = null;
        serverAddress = "127.0.0.1";
        int serverPort = 8008;
        if (args.length >= 2) {
            serverAddress = args[0]; // 从命令行参数获取 IP 地址
            serverPort = Integer.parseInt(args[1]); // 从命令行参数获取端口号
        }
        // 创建客户端对象
        TCPClient client = new TCPClient(serverAddress, serverPort);
        // 通过客户端对象进行通信
        client.send("Hello, Server!");
        String receivedMsg = client.receive();
        System.out.println("Received from server: " + receivedMsg);

        // 关闭客户端连接
        client.close();
    }
}
